package com.zq.learn.grpc;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.ServerServiceDefinition;
import io.grpc.stub.StreamObserver;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * HelloServer
 *
 * @author ZhangQi
 * @date 2020/6/1
 */
@Component
public class HelloServer {
  private Server server;
  private Integer port=8777;

  /**
   * 启动方法
   * @throws IOException
   */
  public void start() throws IOException {
    //指定server端口、接口实现，启动服务。
    server= ServerBuilder.forPort(port).addService(new GreeterImpl()).build().start();
    System.out.println("Starting Server");
    //定义服务停止的钩子，用于监听停止事件。
    Runnable runnable=()->{
      System.err.println("*** shutting down gRPC server since JVM is shutting down");
      try {
        //调用延时停止服务方法
        HelloServer.this.stop();
      } catch (InterruptedException e) {
        e.printStackTrace(System.err);
      }
      System.err.println("*** server shut down");
    };
    Runtime.getRuntime().addShutdownHook(new Thread(runnable));
  }

  /**
   * 延时停止方法
   * @throws InterruptedException
   */
  private void stop() throws InterruptedException {
    if (server != null) {
      server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
    }
  }

  /**
   * 阻塞直到结束方法
   * @throws InterruptedException
   */
  public void blockUntilShutdown() throws InterruptedException {
    if (server != null){
      server.awaitTermination();
    }
  }

  /**
   * 继承抽象类
   */
  private class GreeterImpl extends GreeterGrpc.GreeterImplBase{
    /**
     * 重写抽象方法
     * @param request
     * @param responseObserver
     */
    @Override
    public void sayHi(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
      HelloResponse response =
        HelloResponse.newBuilder().setMessage("Hello," + request.getName()).build();
      responseObserver.onNext(response);
      responseObserver.onCompleted();
    }
  }
}
